package middleware

import (
	"context"
	_const "github.com/flipped-aurora/gin-vue-admin/server/global/const"
	"github.com/gin-gonic/gin"
	"github.com/rs/xid"
)

// LogIDMiddleware 全链路log_id的中间件，从header中取出x-log-id，并设置到ctx中
func LogIDMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 尝试从请求头获取 log_id（用于跨服务调用）
		logID := c.GetHeader(_const.LogIdHeaderKey)
		if logID == "" {
			logID = xid.New().String()
		}
		c.Set(_const.LogIDKey, logID)

		ctx := context.WithValue(c.Request.Context(), _const.LogIDKey, logID)
		c.Request = c.Request.WithContext(ctx)

		c.Next()
	}
}
